package cn.net.withub.dataCollector.common.utils;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Properties;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings({"unused","resource"})
public class FileUtil {
    private static Logger log = Logger.getLogger(FileUtil.class);


    private static String resource_path = CommonProperties.getWebRootPath()+"/src/main/webapp/jsp/common/js/resource/";

    /**
     * 向文本文件中写入内容或追加新内容,如果append为true则直接追加新内容,<br>
     * 如果append为false则覆盖原来的内容<br>
     *
     * @param pathAndFileName	: 文件路径和文件名称
     * @param content			：内容
     * @param append			：是否追加文件内容
     * @return boolean : true is sucess, false is not
     */
    public static boolean writeFileNoneException(String pathAndFileName, String content,boolean append){
        boolean ret = false;
        try {
            FileUtil.writeFile(pathAndFileName, content, append);
            ret = true;
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return ret;
    }
    /**
     * 向文本文件中写入内容或追加新内容,如果append为true则直接追加新内容,<br>
     * 如果append为false则覆盖原来的内容<br>
     *
     * @param path
     * @param content
     * @param append
     * @throws IOException
     */
    public static void writeFile(String path, String content, boolean append)
            throws IOException {
        // 通过这个对象来判断是否向文本文件中追加内容
        File writefile = new File(path);
        // 如果文本文件不存在则创建它
        if (writefile.exists() == false) {
            if(mkDirectory(path.substring(0, path.lastIndexOf("/")))){
                writefile.createNewFile();
                writefile = new File(path); // 重新实例化
            }
        }
        FileOutputStream fw = new FileOutputStream(writefile);
        fw.write(content.getBytes("UTF-8"));
        fw.flush();
        fw.close();
    }

    /**
     * 根据路径创建一系列的目录
     * @param path 完整路径
     * @return 是否成功
     */
    public static boolean mkDirectory(String path){
        File file = null;
        try{
            file = new File(path);
            if (!file.exists()){
                return file.mkdirs();
            }
        }catch (RuntimeException e){
            e.printStackTrace();
        }finally{
            file = null;
        }
        return false;
    }

    //读取文件
    public static String readFile(String path) throws IOException{
        File file=new File(path);
        if(!file.exists()||file.isDirectory())
            throw new FileNotFoundException();
        BufferedReader br=new BufferedReader(new FileReader(file));
        String temp=null;
        StringBuffer sb=new StringBuffer();
        temp=br.readLine();
        while(temp!=null){
            sb.append(temp+" ");
            temp=br.readLine();
        }
        return sb.toString();
    }

    //读取文件
    public static String staticReadFile(String path) {
        try{
            File file=new File(path);
            if(!file.exists()||file.isDirectory())
                throw new FileNotFoundException();
            BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
            String temp=null;
            StringBuffer sb=new StringBuffer();
            temp=br.readLine();
            while(temp!=null){
                sb.append(temp+" ");
//	              sb.append(new String(temp.getBytes("ISO-8859-1"),"UTF-8"));
                temp=br.readLine();
            }
            return sb.toString();
        }catch(Exception e){
            e.printStackTrace();
            return "[]";
        }
    }

    /**
     * 自动load  class path 下面的属性文件
     * @param conf
     * @param p
     */
    public static void loadProp(String conf, Properties p){
        InputStream is = null;
        try{
            is = getInputStream(conf);
            if (null != is){
                p.load(is);
            }
        }catch (IOException e){
            log.warn("Exception happened in loadProp() " + conf, e);
        }
        finally{
            if (null != is){
                try{
                    is.close();
                }catch (IOException e){
                    log.warn("Exception happened in loadProperty()" + conf, e);
                }
            }
        }
    }

    public static InputStream getInputStream(String path)
            throws IOException
    {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        if (null == is)
        {
            throw new FileNotFoundException(path + " cannot be opened because it does not exist");
        }
        return is;
    }


    public static void writeFile(HttpServletResponse response,String filePath,String fileName)throws Exception{
        response.reset();// 不加这一句的话会出现下载错误
        response.setContentType("application/vnd.ms-excel");   // 定义输出类型
        response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileName.getBytes("gbk"),"iso-8859-1"));

        InputStream inputStream = new FileInputStream(new File(filePath));//File.separator
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }

        //关闭流。
        os.close();
        inputStream.close();
    }

    /**
     * 删除单个文件
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) throws Exception{
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }
    /**
     * <p>将base64字符解码保存文件</p>
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code,String targetPath) throws Exception {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }
    /**
     * <p>将base64字符保存文本文件</p>
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void toFile(String base64Code,String targetPath) throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }


    public static void main(String[] args){
        try {
            //writeFile("c:/testLog/tt.sql","中弹的的",true);
            String str = encodeBase64File("G:\\Xftp\\Temporary\\111.jpg");

            System.out.println(str);
            decoderBase64File(str, "G:\\image\\testImg.jpg");

            System.out.println("8888");

            //FtpUtils.download("/home/lwj/", "111.jpg");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
